// 监听手机网络变化
import store from '../../store'
import {
	Network_Online,
	Network_Offline,
	setNetworkState,
	NetworkChangeEventName
} from './config'
import {Network} from './Network.js'
import {Task, Trigger, TaskState} from './Task.js'
import siteInspectionTask from './task/siteInspection.js'
let networkState
const networkChangedTasks = [
	new Task('巡检离线数据提交任务', siteInspectionTask, Trigger.NetworkConnected, {}), // 巡检离线数据提交任务
]

/**
 * 注册网络状态变化事件监听
 */
export function registryNetworkStateChange() {
	console.warn('注册网络状态变化事件监听')
	if(networkState && networkState.initialized){
		return
	}
	uni.getNetworkType({
		success: function (res) {
			console.log('当前网络类型', res.networkType);
			//注册网络状态变更监听事件
			networkState = new Network(res.networkType)
			uni.onNetworkStatusChange(function(res) {
				networkState.state = res.networkType
				console.warn('设备当前网络在线ui别结果', networkState.state)
				store.commit('SET_USERISOFFINE',networkState.state)
				
				if(networkState.isConnected) {
					console.warn('网络状态切换：离线->在线')
					networkChangedTasks
						.filter(t=>{
							return t.trigger === Trigger.NetworkConnected
							    && t.state   !== TaskState.Pending
						})
						.forEach(t=>t.execute())
				} else if (networkState.isDisconnected) {
					console.warn('网络状态切换：在线->离线')
					networkChangedTasks
						.filter(t=>{
							return t.trigger === Trigger.NetworkDisconnected
							    && t.state   !== TaskState.Pending
						})
						.forEach(t=>t.execute())
				}
			})
		}
	})
	
}

export function networkOnline() {
	return networkState ? networkState.online : true
}

export function registryTask(handler) {
	const t = networkChangedTasks.find(task=>task.handler === handler)
	if(!t) {
		throw new Error(`[registryTask][${handler.name}] 未配置`)
	}
	t.active()
}




